package tuiLayer;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Scanner;

import javax.swing.text.html.HTMLDocument.Iterator;

import modelLayer.*;
import controlLayer.*;


public class SaleUI{
    Scanner keyboard = new Scanner(System.in);
    SaleController saleController = new SaleController();
    ItemController itemController = new ItemController();
    CustomerController customerController = new CustomerController();
    String errorMessage = "Incorrect command!";
    private String message="";
    String username;
    Sale sale;
    int cprNo;
    HashMap<Integer, Integer> line = new HashMap<>();
    
    MainUI mainUI;
    
    public SaleUI(){
        
        writeSaleMenu();
        
    }
    public void writeSaleMenu(){
        System.out.println("\f***Start sale Menu***");
        System.out.println(" (1) Add employee(ex: Janis");
        System.out.println(" (2) Return to main menu");
        
        String choice = getString();
        
        switch(choice){
            case "1":
               addEmployee();
               break;
            case "2":
                mainUI = new MainUI();
                mainUI.writeMainMenu();
                break;
            default:
                System.out.println(errorMessage);
                pressEnter();
               // writeMainMenu();
        }
    }
    private void addEmployee(){
        System.out.println("\fEnter username: ");
        username = getString();
        while(saleController.addStaff(username) == null){
            System.out.println("\fEnter valid username! ");
            username = getString();
        }
        pressEnter();
        addCustomer();
    }
    private void addCustomer(){
        System.out.println("\fEnter cprNo(0 if no customer or 12 for exemple): ");
        cprNo = Integer.parseInt(getString());
        while(saleController.addCustomer(cprNo) == null && cprNo != 0){
            System.out.println("\fEnter valid CPR No. (0 if no customer): ");
            cprNo = Integer.parseInt(getString());
        }
        pressEnter();
        addItem();
    }
    private void addItem(){     
        
        
        boolean quit = false;
        System.out.println("\f***Start sale Menu***");
        System.out.println("Enter barcode or ID of product: (ex: 1,2 or 99)");
        int barcode = Integer.parseInt(getString());
        while(saleController.findItemByBarcode(barcode) == null){
            System.out.println("Enter valid barcode!");
            barcode = Integer.parseInt(getString());
        }
        
        if(itemController.findItem(barcode) instanceof Set){
             itemController.findItem(barcode).setQuantity( itemController.makeSetQuantity(barcode, itemController.findItem(barcode)));           
        }
        
        
        if(saleController.findItemByBarcode(barcode).getQuantity()>0){
        if(line.get(barcode)==null){
        saleController.findItemByBarcode(barcode).setQuantity(saleController.findItemByBarcode(barcode).getQuantity()-1);
       if(itemController.findItem(barcode) instanceof Set)
        for(Item i: itemController.getAllItems()){
            if(i.getBarcode()==barcode){
            for(Integer in: ((Set)i).getSetItems()) {
                itemController.findItem(in).setQuantity(itemController.findItem(in).getQuantity()-1);
            }
        }
        }
        line.put(barcode, 1);        
        }           
        }else System.out.println("No more items in stock.");
        pressEnter();
        while(!quit){
            System.out.println("***\fItem Barcode Menu***");
            System.out.println(" (1) Enter barcode or ID of product:  ");
            System.out.println(" (2) Finish Sale ");
            System.out.println(" (3) Cancel Sale");
            String choice = getString();
            switch(choice){
                case "1":
                    System.out.println("\fEnter barcode or ID of product: ");
                    barcode = Integer.parseInt(getString());
                while(saleController.findItemByBarcode(barcode) == null){
                    System.out.println("\fEnter valid barcode!");
                    barcode = Integer.parseInt(getString());
                }
               
                if(itemController.findItem(barcode) instanceof Set){                   
                    itemController.findItem(barcode).setQuantity( itemController.makeSetQuantity(barcode, itemController.findItem(barcode)));
                    }
                if(saleController.findItemByBarcode(barcode).getQuantity()>0){
                     if(line.get(barcode) != null){    
                         line.put(barcode, line.get(barcode) +1);
                         saleController.findItemByBarcode(barcode).setQuantity(saleController.findItemByBarcode(barcode).getQuantity()-1);
                     } else {
                         saleController.findItemByBarcode(barcode).setQuantity(saleController.findItemByBarcode(barcode).getQuantity()-1);
                         line.put(barcode, 1);                     
                     }
                }else System.out.println("\fNo more items in stock.");
                break;
                case "2":
                    makePayment();
                    quit=true;
                    break;
                case "3":
                    saleController.cancelSale(line);
                    quit=true;
                    break;
            }
            pressEnter();
        }
        writeSaleMenu();
    }
    public void makePayment(){
        boolean quit = false;
        double amount;
        String announcer = "";
        sale = saleController.makeSale(username, cprNo, line);
        while(!quit){
            System.out.println("\fPrice: " + sale.getTotalPrice());
            System.out.println("Enter Money! ");
            amount = Double.parseDouble(getString());
            announcer = saleController.makePayment(sale, amount);
            if(!announcer.equals("Not Done Yet! More Money!")){
                quit = true;
            System.out.println(announcer);
            printReceipt(sale, amount);
            }
        }
    }
    
    private void printReceipt(Sale sale,double amount){
        boolean quit = false;
        ArrayList<SaleLine> saleLines = sale.getSaleLines();
        Date date = new Date();
        System.out.println("\f###################");
        System.out.println("***** Reciept *****");
        System.out.println("Item x Quantity"+ "\tPrice");
        for(int i=0; i < saleLines.size(); i++ ){
            SaleLine sL = saleLines.get(i);
            //System.out.print("" + (i+1) + " ");
            System.out.print(saleController.findItemByBarcode(sL.getBarcode()).getName() + " x " + sL.getQuantity());
            System.out.println("\t" + sL.getPrice());
            if(itemController.findItem(saleLines.get(i).getBarcode()) instanceof Set){
            for(Integer setItems: ((Set)itemController.findItem(saleLines.get(i).getBarcode())).getSetItems()){
            System.out.println("\t\t"+itemController.findItem(setItems).getName());
            }
            }
        }
        java.util.Iterator<Integer> itr = line.keySet().iterator();
        while(itr.hasNext()){ // while it still has keys to search for 
            int barcode = (int)itr.next();
            }
        System.out.print("\nAssisted By: "+ sale.getStaff().getName());
        if(customerController.findCustomer(cprNo)!=null)
        {
            System.out.print("\nCustomer name: "+customerController.findCustomer(cprNo).getName());
        //  System.out.print("\nIs craftsman: "+customerController.findCustomer(cprNo).getIsCraftsman());
        }
        System.out.println("\nDate of Purchase: "+ date.getDay() + "-" + date.getMonth() + "-" + (date.getYear()+1900) + '\n');
        System.out.println("*** Money Paid: " + amount);
        System.out.println("*** Price: " + sale.getTotalPrice());
        System.out.println("*** Change due: " + (amount - sale.getTotalPrice()));
        System.out.println("###################");
    }
    
    private void pressEnter(){
        Scanner scanner = new Scanner(System.in);
        System.out.println("Press enter to continue.");
        scanner.nextLine(); 
    }
    private String getString(){
        String startChoice ;
        startChoice = keyboard.next();
        String choice = startChoice.trim();
        return choice;
    }
}